package com.ibm.workplace.wcm.cqplugin.ui.dialogs;

import java.io.*;
import java.util.*;
import java.util.List;
import java.util.regex.*;
import java.util.regex.Pattern;

import org.eclipse.core.runtime.jobs.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.jface.window.*;
import org.eclipse.swt.*;
import org.eclipse.swt.browser.*;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.actions.*;

import com.ibm.workplace.wcm.cqplugin.*;
import com.ibm.workplace.wcm.cqplugin.cq.*;
import com.ibm.workplace.wcm.cqplugin.preference.*;
import com.ibm.workplace.wcm.cqplugin.ui.actions.*;
//import com.ibm.buginfo.ui.misc.*;
import com.ibm.collaboration.realtime.people.*;
import com.ibm.collaboration.realtime.people.ui.*;
import com.ibm.httptest.html.HTMLManager;
import com.ibm.httptest.script.HTMLFailureException;
import com.ibm.httptest.script.TestFailureException;
//import com.ibm.collaboration.realtime.servicehub.*;
import com.ibm.rcp.jface.action.*; 
import com.ibm.rcp.swt.swidgets.*;

public class BugViewDialog extends Window implements LocationListener, CTabFolderListener, ShellListener, ControlListener, IShellProvider, ISelectionProvider {

    private String title;

    private CTabFolder tabFolder;

    private boolean ignoreResize = false; // flag to control whether resive events should be ignored

    /**
     * @param parentShell
     * @param messages - the list of messages to display. This list can contain String or Throwable objects.
     * 
     */
    public BugViewDialog(Shell parentShell) {
        super(parentShell);

        setShellStyle(getShellStyle() | SWT.RESIZE | SWT.MIN | SWT.MAX | SWT.MODELESS);
    }

    public void create() {
        super.create();

        if (getShell() != null) {
            if (title != null) {
                getShell().setText(title);
            }
            getShell().setImage(Activator.getImage(Activator.IMAGE_BUG_VIEW));
            getShell().addControlListener(this);
        }
    }

    protected Control createContents(Composite arg0) {
        Composite composite = new Composite(arg0, 0);
        GridLayout layout = new GridLayout(1, false);
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        composite.setLayout(layout);
        composite.setLayoutData(new GridData(GridData.FILL_BOTH));

        tabFolder = new CTabFolder(composite, SWT.TOP | SWT.BORDER | SWT.FLAT);
        tabFolder.setSimple(false);
        tabFolder.setBorderVisible(true);
        tabFolder.setUnselectedImageVisible(false);
        GridData data = new GridData(GridData.FILL_BOTH);
        tabFolder.setLayoutData(data);
        tabFolder.addCTabFolderListener(this);

        String title = calculateShellTitle();
        getShell().setText(title);
        getShell().setMaximized(true);

        return composite;
    }
    
    public void changed(LocationEvent event) {

    }

    public void changing(LocationEvent event) {
        if (event.location.startsWith("chat://")) {
            event.doit = false;

            String email = event.location.substring("chat://".length());
            if (email.endsWith("/")) {
                email = email.substring(0, email.length() - 1);
            }
            /*kevin
            Person p = Activator.getPerson(email);
            if (p != null) {
                try {
                    PeopleService peopleSvc = (PeopleService) ServiceHub.getService(PeopleService.SERVICE_TYPE);
                    peopleSvc.createConversation(p);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            */
        }
    }

    public void showBugs(IBugInfo[] bugs) {
        if (bugs != null) {
            for (int i = 0; i < bugs.length; i++) {
                showBug(bugs[i]);
            }
        }
    }

    public void showBug(final IBugInfo bugInfo) {
        showBug(bugInfo, false);
    }

    public void showBug(final IBugInfo bugInfo, boolean reloadIfShowing) {
        if (bugInfo == null) return;

        try {
            int tabIndex = -1;

            for (int i = 0; i < tabFolder.getItemCount(); i++) {
                CTabItem tabItem = tabFolder.getItem(i);
                if (tabItem.getData() != null) {
                    IBugInfo tabBugInfo = (IBugInfo) tabItem.getData();
                    if (tabBugInfo != null && tabBugInfo.equals(bugInfo)) {
                        tabIndex = i;
                        break;
                    }
                }
            }

            boolean load = false;

            final CTabItem tabItem;
            //final Browser browser;
            final BugDetailsComposite detailsComposite;

            if (tabIndex != -1) {
                load = reloadIfShowing;
                tabFolder.setSelection(tabIndex);

                tabItem = tabFolder.getItem(tabIndex);
                detailsComposite = (BugDetailsComposite) tabItem.getControl();
            } else {
                load = true;

                tabItem = new CTabItem(tabFolder, SWT.CLOSE);
                tabItem.setText("Loading...");
                tabItem.setImage(Activator.getImage(Activator.IMAGE_BUG));
                tabItem.setData(bugInfo);

                detailsComposite = new BugDetailsComposite(tabItem.getParent(), this);
                GridData data = new GridData(GridData.FILL_BOTH);
                detailsComposite.setLayoutData(data);

                tabItem.setControl(detailsComposite);
                tabFolder.setSelection(tabItem);

                detailsComposite.getBrowser().addLocationListener(this);
                detailsComposite.getBrowser().addControlListener(this);
            }

            detailsComposite.getBrowser().setFocus();

            // Unminimize the window if it's minimized - not sure this is actually working!               
            if (getShell().getMinimized()) {
                getShell().setMinimized(false);
            }
            getShell().setActive();

            if (load) {
                // Contents that show the "Loading..." message
                StringBuffer defaultContents = new StringBuffer("<html><span style='font-family: tahoma; font-size: 8pt; fo1nt-weight: bold'><center>");
                /*kevin
                File pif = Activator.getProgressImageFile();
                if (pif != null) {
                    defaultContents.append("<img valign=middle src='");
                    defaultContents.append(pif.toURI().toURL().toExternalForm());
                    defaultContents.append("'><br>&nbsp;");
                }
                */
                defaultContents.append("<br>Loading details for <b>");
                defaultContents.append(bugInfo.getId());
                defaultContents.append("</b> ...</span></html>");
                detailsComposite.getBrowser().setText(defaultContents.toString());
                
                //modified by Kevin
                final GetBugDetailsJob job = new GetBugDetailsJob("getbugdetails", bugInfo.getDefectlink(), new CqDefectSearchEngine());
                job.addJobChangeListener(new JobChangeAdapter() {

                    public void done(IJobChangeEvent event) {
                    	if(Activator.DEBUG_ON)
                    		System.out.println("showBug: JobChangeAdapter: done(): event: " + event.toString());
                        final String details = job.getBugDetails();
                        //System.out.println("details: " + details);
                        
                        Display.getDefault().asyncExec(new Runnable() {

                            public void run() {
                            	try {
                            		if (!detailsComposite.getBrowser().isDisposed()) {
                            			setBrowserContent(detailsComposite.getBrowser(), details != null ? details : "", bugInfo);
                            			//IConnectionProfile[] profiles = Activator.getDefault().getConnectionProfiles();
                            			tabItem.setText(bugInfo.getId() /*+ (profiles != null && profiles.length > 0 ? " (" + bugInfo.getConnectionProfile().getName() + ")" : "")*/);

                            			detailsComposite.setPersons(findPeopleInDefect(bugInfo, details));

                            			String title = calculateShellTitle();
                            			getShell().setText(title);
                            		}//end if
                            	}catch (Exception e) {
                            		e.printStackTrace();
                            	}
                            }
                        });
                    }

                });

                job.schedule();

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    // Method to handle case when a tab closes
    public void itemClosed(CTabFolderEvent event) {
        if (!tabFolder.isDisposed() && !tabFolder.getShell().isDisposed() && tabFolder.getShell().isVisible()) {
            if (tabFolder.getItemCount() <= 1) {
                event.doit = false;
                tabFolder.getShell().close();
            } else {
                String title = calculateShellTitle((CTabItem) event.item);
                getShell().setText(title);
            }
        }
    }

    private String calculateShellTitle() {
        return calculateShellTitle(null);
    }

    private String calculateShellTitle(CTabItem itemToExclude) {
        String title = null;

        int tabCount = tabFolder.getItemCount() - (itemToExclude != null ? 1 : 0);

        if (tabFolder != null) {
            if (tabCount == 1) {
                title = tabFolder.getItems()[0].getText();
            } else if (tabCount > 1) {
                /*title = "";
                 for (int i = 0; i < tabFolder.getItemCount(); i++) {
                 if (tabFolder.getItems()[i] != itemToExclude) {
                 IBugInfo bugInfo = (IBugInfo) tabFolder.getItem(i).getData();
                 title = title + bugInfo.getId() + (i < tabCount - 1 ? ", " : "");
                 }
                 }*/
            }
        }

        return (title != null ? title : "Defects");
    }

    private void setBrowserContent(Browser browser, String value, IBugInfo bugInfo) throws TestFailureException,
	HTMLFailureException{
        String lineSep = System.getProperty("line.separator");

        /*StyledTextPainter painter = new StyledTextPainter(textField);
         //painter.setText(value);
         
         LiveNamesTextPainer painter2 = new LiveNamesTextPainer(textField);
         painter2.setText(value);*/

        StringBuffer buffer = new StringBuffer(value);
        StringBuffer display = new StringBuffer();
/*      
        CmvcUtils.completeHtmlEscape(value, buffer, false);

        value = buffer.toString();

        // Case 1:
        //ownerLogin    roncraig                    originLogin   roncraig            
        int[] case1a = findNamesWithinString(value, Pattern.compile("ownerLogin    (\\w+) "));
        int[] case1b = findNamesWithinString(value, Pattern.compile("originLogin   (\\w+) "));
*/
        //      case 2:
        /*        history:
         addDate              action          userLogin (userName)
         -------------------- --------------- ----------------------------------
         2003/03/17 13:27:54  open            roncraig (Ron Craig 4-4905)
         */
/*
        int[] case2 = findNamesWithinString(value, Pattern.compile("^[. /]{40} (\\w+) \\(.+$"));
        int[] case5 = findNamesWithinString(value, Pattern.compile("Note by (\\w+) .+;"));

        int[] all = combineIntArrays(new Object[] { case1a, case1b, case2, case5 });

        int extra = 0;
        for (int i = 0; i < all.length; i++) {
            String name = value.substring(all[i], value.indexOf(" ", all[i]));
            String email = CmvcUtils.getUserEmailAddress((CmvcConnectionProfile) bugInfo.getConnectionProfile(), name);
            Person p = BugInfoPluginActivator.getPerson(email);
            if (p != null && p.getStatus() > 0) {
                String filePath = "c:/statusImage" + p.getStatus() + ".png";
                if (!(new File(filePath)).exists()) {
                    Image image = p.getStatusImage();
                    ImageLoader imageLoader = new ImageLoader();
                    imageLoader.data = new ImageData[] { image.getImageData() };
                    imageLoader.save(filePath, SWT.IMAGE_PNG);
                }

                String url = "<img src='" + filePath + "'><a style='text-decoration: none; border-bottom: dash 1px green; font-family: tahoma; font-weight: bold; color: green; font-size: 10pt;' href='chat://" + email + "'>";
                String newName = p.getDisplayName();
                buffer.replace(all[i] + extra, all[i] + extra + name.length(), newName);
                buffer.insert(all[i] + extra, url);
                buffer.insert(all[i] + name.length() + extra + url.length() + (newName.length() - name.length()), "</a>");
                extra = extra + url.length() + "</a>".length() + (newName.length() - name.length());
            }
        }
*/
        /*
        FileWriter fw;
        try {
			fw = new FileWriter("d:\\a.html");
			fw.write(buffer.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        */
		
		
		formatBugDetail(buffer, display);
		
		/*
		int j = buffer.indexOf("cqFormItems[\"1\"]");
        buffer.delete(0,j-55);		
		
        boolean isFound = false;
        String subStr;
        int i = -1;
        while (!isFound) {
        	i = buffer.indexOf("<iframe", i+1);
        	System.out.println("i is: " + i);
        	if (i != -1) {
	        	subStr = buffer.substring(i-8, i-3);
	        	System.out.println("subStr is: " + subStr);
	        	if (subStr.compareTo("table") == 0) {
	        		isFound = true;
	        		buffer.delete(i, buffer.length());
	        	}
        	}
        	else {
        		break;
        	}
        }
        */
        /*
        try {
			fw = new FileWriter("d:\\b.html");
			fw.write(buffer.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
        browser.setText("<html><pre style='font-size: 10pt; word-wrap: break-word; white-space: pre-wrap;'>" + display.toString() + "</pre></html>");
    }

    private void formatBugDetail(StringBuffer buffer, StringBuffer display) throws TestFailureException,
	HTMLFailureException{
    
    	StringBuffer line = new StringBuffer(65);
    	
    	char[] charBlank = new char[65];
    	for (int k = 0; k < 65; k++) {
    		charBlank[k] = ' ';
    	}
    	String blank = new String(charBlank);
    	
    	line.replace(0, 65, blank);
        	
    	//modified by linda on 20/11/08
    	
    	String html = buffer.toString();
    	String defectID = HTMLManager.getCorrelationBoundary(html,"'Defect_ID',","</div>");
    	defectID = HTMLManager.getCorrelationBoundary(defectID,"value=\"","\"");
    	line.replace(0, 32, "ID: " + defectID);
    	
    	
    	String state = HTMLManager.getCorrelationBoundary(html,"'State',","</div>");
    	state = HTMLManager.getCorrelationBoundary(state,"value=\"","\"");
    	line.replace(32, 65, "State: " + state + "<br>");
    	
    	
    	display.append(line);
    	line.replace(0, 65, blank);
    	
    	String submitDate =  HTMLManager.getCorrelationBoundary(html,"'Submit_Date',","',");
    	int indx = submitDate.indexOf("'");
    	submitDate = submitDate.substring(indx+1);
    	display.append("Submitted: " + submitDate + "<br>");
    
    	
    	String headline =  HTMLManager.getCorrelationBoundary(html,"'Headline',","</div>");
    	headline = HTMLManager.getCorrelationBoundary(headline,"value=\"","\"");
    	display.append("Headline: " + headline + "<br>");
    
    	
    	String release =  HTMLManager.getCorrelationBoundary(html,"name=\"Product_Releasetab1\"","</option>");
    	release = release.substring(release.lastIndexOf("\">")+2);
    	line.replace(0, 31, "Release: " + release);
    	
    	String build =  HTMLManager.getCorrelationBoundary(html,"'Build',","</div>");
    	build = HTMLManager.getCorrelationBoundary(build,"value=\"","\"");
    	line.replace(32, 65, "Build: " + build + "<br>");
    	
    	display.append(line);
    	line.replace(0, 65, blank);
    	
    	String submitter =  HTMLManager.getCorrelationBoundary(html,"'Submitter.login_name',","</div>");
    	submitter = HTMLManager.getCorrelationBoundary(submitter,"value=\"","\"");
    	line.replace(0, 31, "Submitter: " + submitter);
    	
    	//String owner =  HTMLManager.getCorrelationBoundary(html,"'Owner',","</div>");
    	//owner = HTMLManager.getCorrelationBoundary(owner,"value=\"","\"");
    	String owner =  HTMLManager.getCorrelationBoundary(html,"value=\"", "name=\"Ownertab1CB\"");
    	owner = owner.substring(0,owner.indexOf("\""));
    	line.replace(32, 65, "Assignee: " + owner + "<br>");
    	
    	display.append(line);
    	line.replace(0, 65, blank); 
    	
    	String test_type =  HTMLManager.getCorrelationBoundary(html,"name=\"Test_Typetab1\"","</option>");
    	test_type = test_type.substring(test_type.lastIndexOf("\">")+2);
    	line.replace(0, 31, "Source: " + test_type);
    	
    	String pmr =  HTMLManager.getCorrelationBoundary(html,"'PMR',","</div>");
    	pmr = HTMLManager.getCorrelationBoundary(pmr,"value=\"","\"");
    	line.replace(32, 65, "PMR: " + pmr + "<br>");
    	
    	display.append(line);
    	line.replace(0, 65, blank);   
    	
    	//String sev =  HTMLManager.getCorrelationBoundary(html,"'Severity',","</div>");
    	//sev = HTMLManager.getCorrelationBoundary(sev,"value=\"","\"");
    	String sev =  HTMLManager.getCorrelationBoundary(html,"value=\"", "name=\"Severitytab1CB\"");
    	sev = sev.substring(0,sev.indexOf("\""));
    	line.replace(0, 31, "Severity: " + sev);
    	
    	//String priority =  HTMLManager.getCorrelationBoundary(html,"'Priority',","</div>");
    	//priority = HTMLManager.getCorrelationBoundary(priority,"value=\"","\"");
    	String priority =  HTMLManager.getCorrelationBoundary(html,"value=\"", "name=\"Prioritytab1CB\"");
    	priority = priority.substring(0,priority.indexOf("\""));
    	line.replace(32, 65, "Priority: " + priority + "<br>");

    	display.append(line);
    	line.replace(0, 65, blank); 
    	
    	String frequency =  HTMLManager.getCorrelationBoundary(html,"value=\"", "name=\"Frequencytab1CB\"");
    	frequency = frequency.substring(0,frequency.indexOf("\""));
    	display.append("Frequency: " + frequency + "<br>");
    	
    	String blocked =  HTMLManager.getCorrelationBoundary(html,"value=\"", "name=\"Blockedtab1\"");
    	blocked = blocked.substring(0,blocked.indexOf("\""));
    	line.replace(0, 31, "Blocking: " + blocked);
    	
    	String pointsBlocked =  HTMLManager.getCorrelationBoundary(html,"value=\"", "name=\"PointsBlockedtab1\"");
    	pointsBlocked = pointsBlocked.substring(0,pointsBlocked.indexOf("\""));
    	line.replace(32, 65, "Blocked Points: " + pointsBlocked + "<br>");

    	display.append(line);
    	line.replace(0, 65, blank);
    	
    	display.append("\n<b>Summary + Steps to reproduce</b><br>");
    	
    	String description =  HTMLManager.getCorrelationBoundary(html,"'Description',","</div>");
    	description = description.substring(description.lastIndexOf("\">")+2);
    	description = description.substring(0,description.indexOf("</"));
    	display.append(description + "<br>"); 
    	
    	display.append("\n<b>Notes Log</b><br>");
    	
    	String notesLog =  HTMLManager.getCorrelationBoundary(html,"name=\"Notes_Logtab3\"","<div");
    	notesLog = notesLog.substring(notesLog.indexOf("\">")+2,notesLog.indexOf("</"));
    	display.append(notesLog + "<br>");
    	
    	display.append("\n<b>Keywords</b><br>");
    	
    	String keywords =  HTMLManager.getCorrelationBoundary(html,"name=\"Keywordstab3\"","<div");
    	keywords = keywords.substring(keywords.indexOf("\">")+2,keywords.indexOf("</"));
    	display.append(keywords + "<br>");
    	     	
    	
	}

	private int[] findNamesWithinString(String string, Pattern pattern) {
        return findNamesWithinString(string, pattern, 0);
    }

    private int[] findNamesWithinString(String string, Pattern pattern, int offset) {
        List ret = new ArrayList();

        Matcher m = pattern.matcher(string);
        while (m.find()) {
            String entireString = m.group(0);      
            if(Activator.DEBUG_ON)
            	System.out.println("found group: !" + entireString + "!");

            String name = m.group(1);
            if(Activator.DEBUG_ON)
            	System.out.println("found name: !" + name + "!");

            ret.add(new Integer(m.start(1) + offset));
        }

        int index = 0;
        int[] array = new int[ret.size()];
        for (Iterator iter = ret.iterator(); iter.hasNext(); index++) {
            Integer i = (Integer) iter.next();
            array[index] = i.intValue();
        }
        return array;
    }

    private Person[] findPeopleInDefect(IBugInfo bugInfo, String bugDetails) {
        HashSet emailAddresses = new HashSet();

        if (bugInfo != null) {
            if (bugInfo.getOriginatorEmailAddress() != null) emailAddresses.add(bugInfo.getOriginatorEmailAddress());
            if (bugInfo.getOwnerEmailAddress() != null) emailAddresses.add(bugInfo.getOwnerEmailAddress());
        }

        if (bugDetails != null && !bugDetails.trim().equals("")) {
            int[] case1a = findNamesWithinString(bugDetails, Pattern.compile("ownerLogin    (\\w+) "));
            int[] case1b = findNamesWithinString(bugDetails, Pattern.compile("originLogin   (\\w+) "));
            int[] case2 = findNamesWithinString(bugDetails, Pattern.compile("^[. /]{40} (\\w+) \\(.+$"));
            int[] case5 = findNamesWithinString(bugDetails, Pattern.compile("Note by (\\w+) "));

            int[] all = combineIntArrays(new Object[] { case1a, case1b, case2, case5 });

            if (all != null && all.length > 0) {
                for (int i = 0; i < all.length; i++) {
                    int startIndex = all[i];
                    int endIndex = bugDetails.indexOf(' ', all[i]);
                    if (startIndex >= 0 && endIndex != -1 && endIndex <= bugDetails.length()) {
                        String userId = bugDetails.substring(all[i], endIndex);
                        //System.out.println("user id: !" + userId + "!");
                        /*
                        String email = CmvcUtils.getUserEmailAddress((CmvcConnectionProfile) bugInfo.getConnectionProfile(), userId);
                        if (email != null && !email.trim().equals("")) {
                            emailAddresses.add(email);
                        }
                        */
                    }
                }
            }
        }
        
        List ret = new ArrayList(emailAddresses.size());

        for (Iterator it = emailAddresses.iterator(); it.hasNext();) {
            String address = (String) it.next();
            if (address.indexOf("nobody@") == -1 && address.indexOf("unknown") == -1) {
                /*
            	Person p = Activator.getPerson(address);
                if (p != null) {
                    ret.add(p);
                }
                */
            }
        }

        return (Person[]) ret.toArray(new Person[ret.size()]);
    }

    private static int[] combineIntArrays(Object[] arrays) {
        int size = 0;
        for (int i = 0; i < arrays.length; i++) {
            int[] temp = (int[]) arrays[i];
            size += temp.length;
        }

        int[] all = new int[size];

        int startIndex = 0;
        for (int i = 0; i < arrays.length; i++) {
            int[] temp = (int[]) arrays[i];
            System.arraycopy(temp, 0, all, startIndex, temp.length);
            startIndex += temp.length;
        }

        return all;
    }

    public void shellActivated(ShellEvent arg0) {
    }

    public void shellClosed(ShellEvent event) {
    }

    public void shellDeactivated(ShellEvent arg0) {
    }

    public void shellDeiconified(ShellEvent arg0) {
    }

    public void shellIconified(ShellEvent arg0) {
    }

    public void controlMoved(ControlEvent event) {
        Shell shell = ((Control) event.widget).getShell();
        saveShellPreferences(shell);
    }

    public void controlResized(ControlEvent event) {
        if (ignoreResize) return;

        if (event.getSource() instanceof Browser) {
            ignoreResize = true;
 
            try {
                Browser browser = (Browser) event.getSource();
                if (browser.getParent() instanceof SashForm) {
                    SashForm sashForm = (SashForm) browser.getParent();
                    int[] newWeights = sashForm.getWeights();

                    Activator.getDefault().getPreferenceStore().setValue(BugInfoPreferenceConstants.PREF_BUG_WINDOW_DETAILS_AREA_WIDTH, newWeights[0]);
                    Activator.getDefault().getPreferenceStore().setValue(BugInfoPreferenceConstants.PREF_BUG_WINDOW_PEOPLE_AREA_WIDTH, newWeights[1]);

                    for (int i = 0; i < tabFolder.getItemCount(); i++) {
                        CTabItem tab = tabFolder.getItem(i);
                        if (tab != null && !tab.isDisposed() && sashForm.getParent() != tab.getControl() && tab.getControl() instanceof BugDetailsComposite) {
                            BugDetailsComposite bdc = (BugDetailsComposite) tab.getControl();
                            if (bdc != null && !bdc.isDisposed()) {
                                bdc.getSashForm().setWeights(newWeights);
                            }
                        } 
                    }
                }
            } catch (Exception ex) {

            } finally {
                ignoreResize = false;
            }

            //System.out.println("weights: " + sf.getWeights());
        }

        Shell shell = ((Control) event.widget).getShell();
        saveShellPreferences(shell);
    }

    private void saveShellPreferences(Shell shell) {
        Rectangle r = shell.getBounds();

        Activator.getDefault().getPreferenceStore().setValue(BugInfoPreferenceConstants.PREF_BUG_WINDOW_X, r.x);
        Activator.getDefault().getPreferenceStore().setValue(BugInfoPreferenceConstants.PREF_BUG_WINDOW_Y, r.y);
        Activator.getDefault().getPreferenceStore().setValue(BugInfoPreferenceConstants.PREF_BUG_WINDOW_WIDTH, r.width);
        Activator.getDefault().getPreferenceStore().setValue(BugInfoPreferenceConstants.PREF_BUG_WINDOW_HEIGHT, r.height);
    }

    protected Point getInitialLocation(Point arg0) {
        int x = Activator.getDefault().getPreferenceStore().getInt(BugInfoPreferenceConstants.PREF_BUG_WINDOW_X);
        int y = Activator.getDefault().getPreferenceStore().getInt(BugInfoPreferenceConstants.PREF_BUG_WINDOW_Y);

        if (x != -1 && y != -1) {
            return new Point(x, y);
        } else {
            return super.getInitialLocation(arg0);
        }
    }

    protected Point getInitialSize() {
        int width = Activator.getDefault().getPreferenceStore().getInt(BugInfoPreferenceConstants.PREF_BUG_WINDOW_WIDTH);
        int height = Activator.getDefault().getPreferenceStore().getInt(BugInfoPreferenceConstants.PREF_BUG_WINDOW_HEIGHT);
        if(Activator.DEBUG_ON) {
        	System.out.println("width is: " + width);
        	System.out.println("height is: " + height);
        }
        if (width != -1 && height != -1) {
            return new Point(width, height);
        } else {
            //kevin return super.getInitialSize();
        	return new Point(800, 600);
        }
    }
    
    private class RefreshBugInfoAction extends SelectionProviderAction {

        public RefreshBugInfoAction(ISelectionProvider selectionProvider) {
            super(selectionProvider, "Refresh");

            setImageDescriptor(Activator.getDefault().getImageRegistry().getDescriptor(Activator.IMAGE_REFRESH));
        }

        public void run() {
            CTabItem tab = tabFolder.getItem(tabFolder.getSelectionIndex());
            
            if (tab != null && !tab.isDisposed()) {
                IBugInfo bugInfo = (IBugInfo) tab.getData();
                if (bugInfo != null) {
                    showBug(bugInfo, true);
                }
            }
        }
    }

    private static class BugDetailsComposite extends Composite {

        private SashForm sashForm;
        private Browser browser;
        private ToolBar toolbar;
        private Composite cardComposite;

        private ISelectionProvider selectionProvider;

        public BugDetailsComposite(Composite parent, ISelectionProvider selectionProvider) {
            super(parent, 0);

            GridLayout layout = new GridLayout(1, false);
            layout.marginWidth = 0;
            layout.marginHeight = 0;
            layout.verticalSpacing = 0;
            setLayout(layout);

            SToolBarManager mgr = new SToolBarManager(SWT.FLAT);
            SToolBar toolbar = (SToolBar) mgr.createControl2(this);
            toolbar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
            
            /*kevin
            mgr.add(new AddCommentAction(selectionProvider));            
            mgr.add(new ChangeDefectOwnerAction(selectionProvider));*/
            BugViewDialog bvd = (BugViewDialog)selectionProvider;
            mgr.add(bvd.new RefreshBugInfoAction(selectionProvider));
            
            mgr.update(true);

            sashForm = new SashForm(this, SWT.HORIZONTAL);
            //form.getBorderWidth()
            sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
            //System.out.println(form.getLayout());
            //form.setBackground(ColorManager.getInstance(form.getDisplay()).getColor(239, 239, 247));
            //kevin sashForm.setBackground(ColorManager.getInstance(getDisplay()).getColor(173, 186, 206));
            //form.setBackground(getDisplay().getSystemColor(SWT.COLOR_RED));

            browser = new Browser(sashForm, SWT.FLAT);
            browser.setLayoutData(new GridData(GridData.FILL_BOTH));

            cardComposite = new Composite(sashForm, 0);
            GridData data = new GridData(GridData.FILL_VERTICAL);
            data.widthHint = 300;
            cardComposite.setLayoutData(data);
            layout = new GridLayout(1, false);
            layout.marginHeight = 0;
            layout.marginWidth = 0;
            cardComposite.setLayout(layout);
            //kevin cardComposite.setBackground(ColorManager.getInstance(getDisplay()).getColor(239, 239, 247));

            int detailsAreaWidth = Activator.getDefault().getPreferenceStore().getInt(BugInfoPreferenceConstants.PREF_BUG_WINDOW_DETAILS_AREA_WIDTH);
            int personAreaWidth = Activator.getDefault().getPreferenceStore().getInt(BugInfoPreferenceConstants.PREF_BUG_WINDOW_PEOPLE_AREA_WIDTH);
            if (detailsAreaWidth == -1 || personAreaWidth == -1) {
                sashForm.setWeights(new int[] { 5, 2 });
            } else {
            	sashForm.setWeights(new int[] { 5, 2 });
            	//kevin sashForm.setWeights(new int[] { detailsAreaWidth, personAreaWidth });
            }
        }

        public Browser getBrowser() {
            return browser;
        }

        public ToolBar getToolbar() {
            return toolbar;
        }

        public SashForm getSashForm() {
            return sashForm;
        }

        public Composite getCardComposite() {
            return cardComposite;
        }

        public void setPersons(Person[] persons) {
            // dispose all children first
            Control[] children = cardComposite.getChildren();
            if (children != null) {
                for (int i = 0; i < children.length; i++) {
                    if (!children[i].isDisposed()) {
                        children[i].dispose();
                    }
                }
            }
            
            for (int i = 0; i < persons.length; i++) {
                MyBusinessCard card = new MyBusinessCard(cardComposite, 0);
                card.setPerson(persons[i]);
                card.setShowExtraInfo(false);
                card.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
                card.setClosable(false);

                /*                if (i < persons.length - 1) {
                 Label l = new Label(cardComposite, SWT.SEPARATOR | SWT.FLAT | SWT.HORIZONTAL);
                 l.setBackground(ColorManager.getInstance(getDisplay()).getColor(173, 186, 206));
                 l.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
                 }*/
            }

            cardComposite.layout(true);
        }
    }

    public void addSelectionChangedListener(ISelectionChangedListener arg0) {
        return;
    }

    public ISelection getSelection() {
        if (tabFolder.getItemCount() > 0) {
            return new StructuredSelection(tabFolder.getItem(tabFolder.getSelectionIndex()).getData());
        } else {
            return null;
        }
    }

    public void removeSelectionChangedListener(ISelectionChangedListener arg0) {
        return;
    }

    public void setSelection(ISelection arg0) {
        return;
    }

}
